<template>
  <div class="tables-container">
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加餐桌
      </el-button>
    </div>

    <!-- 餐桌列表 -->
    <el-table :data="tables" style="width: 100%" v-loading="loading">
      <el-table-column prop="Number" label="餐桌号" width="120" />
      <el-table-column prop="Capacity" label="容纳人数" width="100" />
      <el-table-column prop="Location" label="位置" width="120" />
      <el-table-column prop="Description" label="描述" />
      <el-table-column prop="Status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.Status)">
            {{ getStatusText(scope.row.Status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="CurrentOrder" label="当前订单" width="120" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button 
            size="small"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑/添加对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加餐桌' : '编辑餐桌'"
      width="30%"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="餐桌号" prop="number">
          <el-input v-model="form.number" />
        </el-form-item>
        
        <el-form-item label="容纳人数" prop="capacity">
          <el-input-number 
            v-model="form.capacity"
            :min="1"
            :max="20"
          />
        </el-form-item>
        
        <el-form-item label="位置" prop="location">
          <el-input v-model="form.location" />
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input
            v-model="form.description"
            type="textarea"
            rows="3"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option label="空闲" value="free" />
            <el-option label="使用中" value="in_use" />
            <el-option label="预订" value="reserved" />
            <el-option label="维护中" value="maintenance" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'

interface Table {
  ID: number
  CreatedAt: string
  UpdatedAt: string
  DeletedAt: string | null
  Number: string
  Capacity: number
  Status: string
  CurrentOrder: string
  Location: string
  Description: string
}

const store = useStore()
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const tables = ref<Table[]>([])
const formRef = ref<FormInstance>()

const form = ref({
  id: 0,
  number: '',
  capacity: 4,
  location: '',
  description: '',
  status: 'free'
})

const rules = {
  number: [{ required: true, message: '请输入餐桌号', trigger: 'blur' }],
  capacity: [{ required: true, message: '请输入容纳人数', trigger: 'blur' }],
  location: [{ required: true, message: '请输入位置', trigger: 'blur' }]
}

// 处理添加
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    id: 0,
    number: '',
    capacity: 4,
    location: '',
    description: '',
    status: 'free'
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (table: Table) => {
  dialogType.value = 'edit'
  form.value = {
    id: table.ID,
    number: table.Number,
    capacity: table.Capacity,
    location: table.Location,
    description: table.Description,
    status: table.Status
  }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = async (table: Table) => {
  try {
    await ElMessageBox.confirm('确定要删除该餐桌吗？', '提示', {
      type: 'warning'
    })
    
    const response = await fetch(`http://localhost:8080/api/tables/${table.ID}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    
    if (response.ok) {
      ElMessage.success('删除成功')
      loadTables()
    } else {
      const data = await response.json()
      ElMessage.error(data.error || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const url = dialogType.value === 'add' 
          ? 'http://localhost:8080/api/tables'
          : `http://localhost:8080/api/tables/${form.value.id}`
        
        const requestBody = {
          number: form.value.number,
          capacity: form.value.capacity,
          location: form.value.location,
          description: form.value.description,
          status: form.value.status
        }
        
        console.log('Submitting table:', requestBody)
        
        const response = await fetch(url, {
          method: dialogType.value === 'add' ? 'POST' : 'PUT',
          headers: {
            'Authorization': `Bearer ${store.state.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(requestBody)
        })
        
        const responseData = await response.json()
        console.log('Submit response:', responseData)
        
        if (response.ok) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          await loadTables()
        } else {
          ElMessage.error(responseData.error || (dialogType.value === 'add' ? '添加失败' : '更新失败'))
        }
      } catch (error) {
        console.error('Submit error:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }
  })
}

const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'free': 'success',
    'in_use': 'warning',
    'reserved': 'info',
    'maintenance': 'danger'
  }
  return statusMap[status] || ''
}

const getStatusText = (status: string) => {
  const statusTextMap: Record<string, string> = {
    'free': '空闲',
    'in_use': '使用中',
    'reserved': '预订',
    'maintenance': '维护中'
  }
  return statusTextMap[status] || status
}

// 加载餐桌列表
const loadTables = async () => {
  loading.value = true
  try {
    console.log('Loading tables...')
    const response = await fetch('http://localhost:8080/api/tables', {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    
    // 打印原始响应
    console.log('Raw response:', response)
    
    const data = await response.json()
    console.log('Response data:', data)
    
    // 检查数据结构
    if (data.tables) {
      console.log('Tables array:', data.tables)
      console.log('First table:', data.tables[0])
    }
    
    if (response.ok && data.tables) {
      tables.value = data.tables
      console.log('Tables loaded:', tables.value)
      
      // 检查表格数据绑定
      console.log('Table component data:', {
        data: tables.value,
        columns: {
          number: tables.value[0]?.number,
          capacity: tables.value[0]?.capacity,
          location: tables.value[0]?.location,
          status: tables.value[0]?.status,
        }
      })
    } else {
      console.error('Error response:', data.error)
      ElMessage.error(data.error || '加载餐桌列表失败')
    }
  } catch (error) {
    console.error('Load tables error:', error)
    ElMessage.error('加载餐桌列表失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadTables()
})
</script>

<style scoped>
.tables-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
}
</style> 